package org.example.myleet.p981;

import org.example.myleet.Utils.Assert;
import org.example.myleet.Utils.JsonUtils;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
        Assert.isTrue(Assert.isPass(
                parse1DArray("[null,null,\"bar\",\"bar\",null,\"bar2\",\"bar2\"]"),
                execute("[\"TimeMap\",\"set\",\"get\",\"get\",\"set\",\"get\",\"get\"]", "[[],[\"foo\",\"bar\",1],[\"foo\",1],[\"foo\",3],[\"foo\",\"bar2\",4],[\"foo\",4],[\"foo\",5]]")));
        Assert.isTrue(Assert.isPass(
                parse1DArray("[null,null,null,\"\",\"high\",\"high\",\"low\",\"low\"]"),
                execute("[\"TimeMap\",\"set\",\"set\",\"get\",\"get\",\"get\",\"get\",\"get\"]", "[[],[\"love\",\"high\",10],[\"love\",\"low\",20],[\"love\",5],[\"love\",10],[\"love\",15],[\"love\",20],[\"love\",25]]")));
    }

    private static List<String> execute(String input1, String input2) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        List<String> steps = parse1DArray(input1);
        List<List<Object>> params = parse2DArray(input2);
        List<String> result = new ArrayList<>();
        result.add(null);
        TimeMap map = new TimeMap();
        for (int i = 1; i < steps.size(); ++i) {
            List<Object> param = params.get(i);
            if ("set".equals(steps.get(i))) {
                Method m = map.getClass().getMethod(steps.get(i), String.class, String.class, int.class);
                result.add((String) m.invoke(map, param.get(0), param.get(1), param.get(2)));
            } else {
                Method m = map.getClass().getMethod(steps.get(i), String.class, int.class);
                result.add((String) m.invoke(map, param.get(0), param.get(1)));
            }
        }
        return result;
    }

    private static List<List<Object>> parse2DArray(String input) {
        return JsonUtils.parse(input, List.class);
    }

    private static List<String> parse1DArray(String input) {
        return JsonUtils.parse(input, List.class);
    }
}
